﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;
using System.Collections.Generic;

namespace UI
{
    /// <summary>
    /// 开服基金，全民福利
    /// </summary>
    public class UIActivityOpenSeverMoney : UIActivityTemplate
    {
        public GameObject openRed;
        public GameObject allRed;
        public GameObject itemPref;
        public SimpleGrid simpleGrid;
        public UIScrollView scrollView;
        public GameObject allPerson;
        public GameObject openSever;
        List<ActivityItem> openList;
        List<ActivityItem> personList;
        public GameObject imgGetted;
        public GameObject imgGettedToo;
        public GameObject buyBtnToo;
        public GameObject buyBtn;
        public List<UILabel> buyNum;
        public UILabel vip;
        int buyState;
        int buyCount;
        int flag;
        int[] canGet = { 0, 0 };
        protected override void PrepareData()
        {
            activityType = ActivityType.OpenSeverMoney;
        }

        public override void Init(UIActivity activity)
        {
            base.Init(activity);
            DataMessageTool.AddHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);
        }

        public override void Show()
        {
            base.Show();
            
            CSOpenServerFundInfo msg = new CSOpenServerFundInfo();
            NetAPI.SendHttp(OpDefine.CSOpenServerFundInfo, msg, MsgCallback);
            ShowOrHideRedPoint(new object());
        }

        public override void OnPageClosed()
        {
            DataMessageTool.RemoveHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);
            base.OnPageClosed();
        }
        void MsgCallback(NetWork.Packets.Packet packet, bool success)
        {
            if (success)
            {
                SCOpenServerFundInfo msg = packet.kBody as SCOpenServerFundInfo;
                openList = msg.openServerFundList;
                personList = msg.everyoneBenefitList;
                buyState = msg.buyStatus;
                SetBuyLabel(msg.buyCount) ;
                SetBtnState(buyState);
                vip.text = "会员" + StaticData.playerData.vip.ToString();
                //两个列表都初始化一次，为了红点……
                flag = 1;
                OnTabClick();
                flag = 0;
                OnTabClick();
            }
        }

        void ShowOrHideRedPoint(object o)
        {
            if (openRed == null)
                return;

            openRed.SetActive(StaticData.redTips.GetStateByType(RedPointTip.Red.openServerFundChild));
            allRed.SetActive(StaticData.redTips.GetStateByType(RedPointTip.Red.allPeopleBoon));
        }

        void SetBtnState(int buyState)
        {
            bool value = (buyState == 2);
            imgGetted.SetActive(value);
            buyBtn.SetActive(!value);
            buyBtnToo.SetActive(!value);
            imgGettedToo.SetActive(value);
        }

        public void AddCanGetNum()
        {
            switch (flag)
            {
                case 0:
                    canGet[0]++;
                    break;
                case 1:
                    canGet[1]++;
                    break;
            }
        }

        public void ResetCanGetNum()
        {
            for (int i = 0; i < canGet.Length; i++)
                switch (flag)
                {
                    case 0:
                        canGet[0] = 0;
                        break;
                    case 1:
                        canGet[1] = 0;
                        break;
                }
        }

        public void SetRedByNum()
        {
            switch (flag)
            {
                case 0:
                    if (canGet[0] < 1)
                    {
                        StaticData.redTips.SetPointState(RedPointTip.Red.openServerFundChild, 0);
                        StaticData.redTips.ReduceActivitys();
                    }
                    break;
                case 1:
                    if (canGet[1] < 1)
                    {
                        StaticData.redTips.SetPointState(RedPointTip.Red.allPeopleBoon, 0);
                        StaticData.redTips.ReduceActivitys();
                    }
                    break;
            }
            if(canGet[0] < 1 && canGet[1] < 1)
            {
                StaticData.redTips.SetPointState(RedPointTip.Red.openServerFund, 0);
                StaticData.redTips.ReduceActivitys();
            }
        }

        //开服基金
        public void OnOpenMoney(List<ActivityItem> list)
        {
            
            foreach (var item in simpleGrid.childs)
                Destroy(item);
            simpleGrid.childs.Clear();
            ResetCanGetNum();
            if (list != null)
            {
                openList = list;
                openList.Sort(delegate (ActivityItem a, ActivityItem b)
                {
                    if (a.index < b.index)
                        return -1;
                    else if (a.index > b.index)
                        return 1;
                    return 0;
                });
            }
            for (int i = 0; i < openList.Count; i++)
            {
                GameObject obj = Instantiate(itemPref);
                obj.SetActive(true);
                simpleGrid.AddChild(obj);
                obj.transform.localScale = Vector3.one;
                var script = obj.GetComponent<OpenSverItem>();
                script.m_addNum = AddCanGetNum;
                script.SetActivityItem(openList[i], activityId, this,0);
            }
            scrollView.ResetPosition();
            SetRedByNum();
            scrollView.ResetPosition();
        }

        //全民福利
        public void OnAllPerson(List<ActivityItem> list)
        {
            foreach (var item in simpleGrid.childs)
                Destroy(item);
            simpleGrid.childs.Clear();
            ResetCanGetNum();
            if (list != null)
            {
                personList = list;
                personList.Sort(delegate (ActivityItem a, ActivityItem b)
                {
                        int weighta = a.status == 1 ? 100 : a.status == 0 ? 50 : 0;
                        int weightb = b.status == 1 ? 100 : b.status == 0 ? 50 : 0; // 0:未达成 1:可领取 2:已领取
                    if (weighta > weightb)
                    {
                        return -1;
                    }
                    else if (weighta  < weightb)
                    {
                        return 1;
                    }
                    else {
                        if (a.index < b.index)
                            return -1;
                        else if (a.index > b.index)
                            return 1;
                        return 0;
                    }
                });
            }
            for (int i = 0; i < personList.Count; i++)
            {
                GameObject obj = Instantiate(itemPref);
                obj.SetActive(true);
                simpleGrid.AddChild(obj);
                obj.transform.localScale = Vector3.one;
                var script = obj.GetComponent<OpenSverItem>();
                script.m_addNum = AddCanGetNum;
                script.SetActivityItem(personList[i], activityId, this,1);
            }
            scrollView.ResetPosition();
            SetRedByNum();
            scrollView.ResetPosition();
        }

        public void OnTabClick(GameObject obj = null)
        {
            
            if(obj != null)
                if (obj.name == "allPeople")
                    flag = 1;
                else
                    flag = 0;
            openSever.SetActive(flag == 0);
            allPerson.SetActive(flag == 1);

            if (flag == 0)
                OnOpenMoney(openList);
            else
                OnAllPerson(personList); 
        }

        public void OnBuyBtnClick()
        {
            if (buyState == 0)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("vip2Level_Limit"));
                return;
            }
            else if (StaticData.playerData.diamond < 1000) {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("diamond_lack"));
                return;
            }
            CSBuyOpenServerFund msg = new CSBuyOpenServerFund();
            NetAPI.SendHttp(OpDefine.CSBuyOpenServerFund, msg, (pack, bSuccess) =>
            {
                if (bSuccess)
                {
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("buy_success"));
                    SCBuyOpenServerFund _msg = pack.kBody as SCBuyOpenServerFund;
                    StaticData.playerData.Delete(_msg.cost);
                    SetBtnState(_msg.buyStatus);
                    SetBuyLabel(_msg.buyCount);
                    openList = _msg.openServerFundList;
                    personList = _msg.everyoneBenefitList;
                    if (flag == 0)
                        OnOpenMoney(openList);
                    else
                        OnAllPerson(personList);
                }
            });
        }

        void SetBuyLabel(int num)
        {
            int[] nums = new int[4];
            if (num > 9999)
                num = 9999;
            int i = 0;

            buyNum[i].text = (num % 10).ToString();
            while (num / 10 > 0)
            {
                num /= 10;
                buyNum[++i].text = (num % 10).ToString();
            }
            for(int j = nums.Length - 1; j > i; j--)
            {
                buyNum[j].text = "0";
            }
        }
    }
}
